const express = require('express')
const router =express.Router()
const OrderModel = require('../models/order')

router.get('/find',(req,res,next)=>{
    const {user_id} = req.query
    if(user_id!=undefined){
      OrderModel.find({user_id}).then(result=>{
        res.json({
            code:200,
            data:result,
            message:'user_id查询成功',
        })
    })}
    else{
      OrderModel.find().then(result=>{
        res.json({
            code:200,
            data:result,
            message:'全局查询成功',
        })
    })}
})

router.post('/create',(req,res,next)=>{
    const {address,garbage,user_id,user_name,service_time,phone,nickname} = req.body
    OrderModel.find().then(result=>{
        const order = new OrderModel({
          order_id:result.length?result[result.length-1].order_id+1:0,
          user_id,
          user_name,
          nickname,
          address,
          garbage:garbage.split(','),
          service_time,
          state:false,
          phone,
          create_time:new Date(new Date().valueOf()+8*60*60*1000),
          end_time:new Date(new Date().valueOf()+8*60*60*1000),
        })
        order.save().then(result => {
            res.json({
                code:200,
                data:{
                    result
                },
                message:'order创建完成',
            })
        })
    })
})

router.post('/update',(req,res,next)=>{
  const {order_id} = req.body
  OrderModel.updateOne({order_id},{$set:{
      "state":true,
      "end_time":new Date(new Date().valueOf()+8*60*60*1000)
    }}).then(result=>{
        res.json({
            code:200,
            data:{
                result
            },
            message:'订单完成',
        })
    })
})

router.post('/updateAll',(req,res,next)=>{
    const {order_id,service_time,garbage,phone,address,user_id,user_name,nickname} = req.body
    OrderModel.updateOne({order_id},{$set:{
        "user_id":user_id,
        "nickname":nickname,
        "address":address,
        "garbage":garbage.split(','),
        "service_time":service_time,
        "phone":phone,
      }}).then(result=>{
          res.json({
              code:200,
              data:{
                  result
              },
              message:'订单完成',
          })
      })
  })

router.delete('/delete',(req,res,next)=>{
  const {order_id} = req.body

  OrderModel.deleteOne({order_id}).then(result=>{
      res.json({
          code:200,
          data:{
              result
          },
          message:'删除完成',
      })
  })
})
module.exports = router